package com.hcb.tonguetiphealth.view;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hcb.tonguetiphealth.adapter.SelectionListAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.Exit;
import com.hcb.tonguetiphealth.manager.WeiboManager;
import com.hcb.tonguetiphealth.model.FileInfo;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.widget.BottomWidget;
import com.hcb.tonguetiphealth.widget.homepage.HomepagePersonalWidget;

public class DIYActivity extends AbstractActivity {

	private EditText etContent;
	private Button btPic,  btShareHealth, btDelPic;
	private TextView tvFileName;
	private LinearLayout llShareWeibo;
	private String fileName = "";
	private ListView dialogListView;
	private Context context;
	private Handler mHandler;
	private boolean resSuccess;
	private String strMessage;
	private FileInfo fileInfo;
	private LinearLayout llback;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.diy);
		context = this;
		new BottomWidget(this);
		setActivity(this);
		bindView();
		bindEvent();
		Exit.add(this);
	}

	private void bindView() {
		etContent = (EditText) findViewById(R.id.diy_content);
		btPic = (Button) findViewById(R.id.diy_upload_pic);
		llShareWeibo = (LinearLayout) findViewById(R.id.diy_share_weibo_ll);
		btShareHealth = (Button) findViewById(R.id.diy_share_health_bt);
		btDelPic = (Button)findViewById(R.id.diy_delpic_bt);
		tvFileName = (TextView)findViewById(R.id.diy_filename_tv);
		llback = (LinearLayout)findViewById(R.id.res_info_back);
		mHandler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch (msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog("正在发送请求..");
					break;
				case MessageWhat.DIMISS_DIALOG:
					if (resSuccess) {
						Toast.makeText(context, "请求成功!", Toast.LENGTH_LONG).show();
						try {
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						Intent intent = new Intent(context, HealthShareActivity.class);
						context.startActivity(intent);
					}else {
						Toast.makeText(context, "请求失败,请稍后重试!", Toast.LENGTH_LONG).show();
					}
					dismissMessageDialog();
					break;
				case MessageWhat.LOGIN:
					showMessageDialog("正在登录...");
					break;
				case MessageWhat.LOGIN_SUCCESS:
					dismissMessageDialog();
					commmitMsg();	
					break;
				case MessageWhat.LOGIN_FAILD:
					dismissMessageDialog();
					String strMsg = (String)msg.obj;
					Toast.makeText(context, strMsg, Toast.LENGTH_LONG).show();
					break;
				case MessageWhat.NETWORK_FAILD:
					dismissMessageDialog();
					showMessageDialog("网络有点不给力哦");
					break;
		
				default:
					break;
				}
			}
			
		};
		setHandler(mHandler);
	}

	private void bindEvent() {
		llback.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		btPic.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showSelectDialog();
			}

		});
		llShareWeibo.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String strContent = etContent.getText().toString().trim();
				if (strContent == null || strContent.equals("")) {
					Toast.makeText(context, "内容不能为空！", Toast.LENGTH_LONG).show();
					return;
				}
				
				String expName = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
				if (fileName== null || fileName.equals("") || "jpg".equals(expName) || "gif".equals(expName) || "png".equals(expName)) {
					WeiboManager weiboManager = new WeiboManager(context);
					weiboManager.setShareContent(strContent);
					weiboManager.setShareCOntentPic(fileName);
					weiboManager.authWeibo();
				}else {
					Toast.makeText(context, "图片格式仅支持jpg,gif,png！", Toast.LENGTH_LONG).show();
					return;
				}
			}

		});
		btShareHealth.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				strMessage = etContent.getText().toString().trim();
				if (strMessage == null || strMessage.equals("")) {
					Toast.makeText(context, "内容不能为空！", Toast.LENGTH_LONG).show();
					return;
				}
				
				String expName = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
				if (fileName== null || fileName.equals("") || "jpg".equals(expName) || "gif".equals(expName) || "png".equals(expName)) {

				}else {
					Toast.makeText(context, "图片格式仅支持jpg,gif,png！", Toast.LENGTH_LONG).show();
					return;
				}
				if (Global.user == null) {
					login();
				}else {
					commmitMsg();	
				}
			}

		});
		btDelPic.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//btDelPic.setVisibility(View.GONE);
//				File file = new File(fileName);
//				if (file.exists()) {
//					file.delete();					
//				}
			    Intent intent = new Intent(DIYActivity.this, PicShowActivity.class);
			    System.out.println("filename"+fileName);
			    intent.putExtra("fileName", fileName);
				startActivity(intent);
				
			}
		});
	}
	
	private void commmitMsg(){
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		new Thread(){
			public void run() {
				List<NameValuePair>params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("userId", Global.user.getUserId()));
				params.add(new BasicNameValuePair("message", strMessage));
				fileInfo = new FileInfo();
				fileInfo.setName("spic");
				fileInfo.setUrl(fileName);
				String response = HttpUtils.PostFile(Global.getServletmsgcommit(), params, fileInfo);
				if(Global.DEBUG){
					System.out.println("发送msg返回信息："+response);
				}
				resSuccess = false;
				if (response != null) {
					try {
						JSONObject jsonObject = new JSONObject(response);
						String strReturn = jsonObject.getString("return");
						if ("true".equals(strReturn)) {
							resSuccess = true;
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
			}
		}.start();
	}
	
	@Override
	public void onBackPressed() {
		finish();
	}

	private void startCamera() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File fileDir1 = this.getFilesDir();
		String path = fileDir1.getParent() + File.separator + "tempPic";
		File fileDir2 = new File(path);
		if (!fileDir2.exists()) {
			fileDir2.mkdir();			
		}
		String  strName  =  "IMG_svenke.jpg";  
		
		//指定调用相机拍照后的照片存储路径
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), strName)));
		this.startActivityForResult(intent, 1);
	}

	private void startLocalFiles(){
		Intent intent = new Intent();
        /* 开启Pictures画面Type设定为image */
        intent.setType("image/*");
        /* 使用Intent.ACTION_GET_CONTENT这个Action */
        intent.setAction(Intent.ACTION_GET_CONTENT); 
        /* 取得相片后返回本画面 */
        startActivityForResult(intent, 2);
	}
	
	public void showSelectDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this); 
        final AlertDialog dialog = builder.create(); 
        /*builder.setPositiveButton("确定",null);    
        builder.setNegativeButton("取消",null); */  
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        
        LayoutInflater li = LayoutInflater.from(this); 
        View view = li.inflate(R.layout.res_book_dialog_list, null); 
   
        dialog.setView(view);
        dialogListView = (ListView)view.findViewById(R.id.selection_listview);
        List<String>selectList = new ArrayList<String>();
    	selectList.add("拍照");
		selectList.add("从本地相册");
		SelectionListAdapter adapter = new SelectionListAdapter(context,
				selectList);
		dialogListView.setAdapter(adapter);
        dialogListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				switch (arg2) {
				case 0:
					startCamera();
					dialog.cancel();
					break;
				case 1:
					startLocalFiles();
					dialog.cancel();
					break;
				default:
					break;
				}
			}
		});
        
        dialog.show(); 
    }
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
			String sdStatus = Environment.getExternalStorageState();
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
				Log.v("TestFile",
						"SD card is not avaiable/writeable right now.");
				Toast.makeText(this, "请插入SD卡", Toast.LENGTH_LONG).show();
				return;
			}
			System.out.println("`````````````````==============");
			File fileDir1 = this.getFilesDir();
			String path = Environment.getExternalStorageDirectory()
					+ File.separator +"IMG_svenke.jpg";
			fileName = path;
			File tmp = new File(path);
			startPhotoZoom(Uri.fromFile(tmp));
			btDelPic.setVisibility(View.VISIBLE);
		} else if (requestCode == 2 && resultCode == Activity.RESULT_OK) {
			Uri uri = data.getData();
			startPhotoZoom(uri);
		}else if (requestCode == 3 && resultCode == Activity.RESULT_OK) {
			setPicToView(data);
		}else {
		}
	}
	
	
	/**
	 * 裁剪图片方法实现
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri){
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		//下面这个crop=true是设置在开启的intent中设置显示的View可裁剪
		intent.putExtra("crop", "true");
		//aspecX aspectY是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		//outputX outputY是裁剪图片宽高
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}
	
	/**
	 * 保存裁剪之后的图片数据
	 * @param picData
	 */
	private void setPicToView(Intent picData){
		Bundle extras = picData.getExtras();
		if (extras != null) {
			Bitmap bitmap = extras.getParcelable("data");
			Drawable drawable = new BitmapDrawable(bitmap);
//			img.setBackgroundDrawable(drawable);
			
			FileOutputStream b = null;

			String path = Environment.getExternalStorageDirectory() + File.separator + "TongueTipHealth" + 
						  File.separator + "tempPic"
						  + File.separator;
			
			File fileDir2 = new File(path);
			fileDir2.mkdir();
			
			String  strName  =  "IMG_tmp.jpg";  
			
			fileName = path + strName;
			try {
				b = new FileOutputStream(fileName);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				try {
					b.flush();
					b.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			fileInfo = new FileInfo();
			fileInfo.setName("spic");
			fileInfo.setUrl(fileName);
		}
	}

	
}